/**
 * Created by tdzl2003 on 6/20/16.
 */

import React, { PropTypes } from 'react';
import FormContext from './FormContext';
import Subscribe from '../Subscribe';

export default class Submit extends React.Component {
  static propTypes = {
    children: PropTypes.element,
  }

  static contextTypes = {
    form: PropTypes.instanceOf(FormContext),
  };

  componentWillMount() {
    this.onSubmitStateChange();
  }

  onSubmitStateChange = () => {
    const { form } = this.context;
    this.setState({
      disabled: form.isSubmitting || !form.isValid,
    });
  };

  onPress = () => {
    this.context.form.submit();
  };

  render() {
    const { children } = this.props;
    const { form } = this.context;
    const onlyChild = React.Children.only(children);

    const result = React.cloneElement(onlyChild, {
      onPress: this.onPress,
      disabled: this.state.disabled,
    });

    return (
      <Subscribe target={form} eventName="onSubmitBegin" listener={this.onSubmitStateChange}>
        <Subscribe target={form} eventName="onSubmitEnd" listener={this.onSubmitStateChange}>
          <Subscribe target={form} eventName="onValueChange" listener={this.onSubmitStateChange}>
            <Subscribe target={form} eventName="onFieldChange" listener={this.onSubmitStateChange}>
              {result}
            </Subscribe>
          </Subscribe>
        </Subscribe>
      </Subscribe>
    );
  }
}
